import { BASE_URL } from "@/config/base.js";

let show = true;
const request = ({ url, method, params, data, headers }) => {
  return new Promise((resolve, reject) => {
    if (!headers) {
      headers = {
        "content-type": "application/json",
        Authorization: "Bearer " + uni.getStorageSync("token"),
      };
    }
    uni.request({
      // '/dev-api' +
      // url: BASE_URL + "/app" + url,
      url: BASE_URL + "/prod-api/app" + url,
      data: data,
      method: method,
      header: headers,
      success: (res) => {
        const { code, msg } = res.data;

        if (code == 200) {
          return resolve(res.data);
        } else if (code == 401) {
          if (show) {
            uni.removeStorageSync("token");
            uni.showModal({
              title: "提示",
              content: "是否登录",
              success: function (res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: "/subPackage/mine/login",
                  });
                }
              },
            });
            show = false;
            setTimeout(() => {
              show = true;
            }, 3000);
          }
          return;
        }
        uni.showToast({
          icon: "none",
          duration: 3000,
          title: msg ? msg : "系统错误",
        });
        return reject(msg);
      },
      fail(error) {
        console.log("请求错误：", error);
        uni.showToast({
          icon: "none",
          duration: 3000,
          title: "网络异常，请稍后重试！",
        });
        return reject(error);
      },
      // 接口调用结束的回调函数（调用成功、失败都会执行）
      complete() {},
    });
  });
};

// 向外暴露request
export default request;
